import React, { useState, useEffect } from 'react';
import {
  Typography,
  Container,
  Box,
  Paper,
  Card,
  CardContent,
  Grid,
  Chip,
  Fade,
  Grow,
  CircularProgress,
  Alert,
} from '@mui/material';
import { styled, keyframes } from '@mui/material/styles';
import {
  LineChart,
  Line,
  XAxis,
  YAxis,
  CartesianGrid,
  Tooltip,
  Legend,
  ResponsiveContainer,
  BarChart,
  Bar,
  PieChart,
  Pie,
  Cell,
} from 'recharts';
import {
  TrendingUp,
  Psychology,
  Analytics,
  Biotech,
  Speed,
  CheckCircle,
  Warning,
  Error as ErrorIcon,
} from '@mui/icons-material';

// 动画关键帧
const fadeInUp = keyframes`
  from {
    opacity: 0;
    transform: translateY(30px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
`;

const pulse = keyframes`
  0% {
    transform: scale(1);
  }
  50% {
    transform: scale(1.05);
  }
  100% {
    transform: scale(1);
  }
`;

// 主容器样式
const MainContainer = styled(Container)(({ theme }) => ({
  background: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)',
  minHeight: '100vh',
  paddingTop: theme.spacing(4),
  paddingBottom: theme.spacing(4),
}));

// 主要内容纸张样式
const MainPaper = styled(Paper)(({ theme }) => ({
  background: 'linear-gradient(145deg, #ffffff 0%, #f8fafc 100%)',
  borderRadius: '24px',
  padding: theme.spacing(4),
  boxShadow: '0 20px 40px rgba(0,0,0,0.1), 0 0 0 1px rgba(255,255,255,0.05)',
  backdropFilter: 'blur(10px)',
  border: '1px solid rgba(255,255,255,0.2)',
  animation: `${fadeInUp} 0.8s ease-out`,
}));

// 标题样式
const GradientTitle = styled(Typography)(({ theme }) => ({
  background: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)',
  WebkitBackgroundClip: 'text',
  WebkitTextFillColor: 'transparent',
  backgroundClip: 'text',
  fontWeight: 800,
  textAlign: 'center',
  marginBottom: theme.spacing(3),
  position: 'relative',
  '&::after': {
    content: '""',
    position: 'absolute',
    bottom: '-10px',
    left: '50%',
    transform: 'translateX(-50%)',
    width: '100px',
    height: '4px',
    background: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)',
    borderRadius: '2px',
  },
}));

// 图表容器样式
const ChartContainer = styled(Box)(({ theme }) => ({
  background: 'linear-gradient(145deg, #ffffff 0%, #f8fafc 100%)',
  borderRadius: '20px',
  padding: theme.spacing(3),
  border: '1px solid rgba(255,255,255,0.2)',
  boxShadow: '0 8px 32px rgba(0,0,0,0.1)',
  height: '400px',
  marginBottom: theme.spacing(3),
}));

// 统计卡片样式
const StatsCard = styled(Card)(({ theme }) => ({
  background: 'linear-gradient(145deg, #ffffff 0%, #f8fafc 100%)',
  borderRadius: '20px',
  padding: theme.spacing(3),
  height: '100%',
  border: '1px solid rgba(255,255,255,0.2)',
  boxShadow: '0 8px 32px rgba(0,0,0,0.1)',
  transition: 'all 0.3s cubic-bezier(0.4, 0, 0.2, 1)',
  cursor: 'pointer',
  position: 'relative',
  overflow: 'hidden',
  '&::before': {
    content: '""',
    position: 'absolute',
    top: 0,
    left: 0,
    right: 0,
    height: '4px',
    background: 'linear-gradient(90deg, #FF6B6B, #4ECDC4, #45B7D1, #96CEB4)',
    borderRadius: '20px 20px 0 0',
  },
  '&:hover': {
    transform: 'translateY(-8px) scale(1.02)',
    boxShadow: '0 20px 40px rgba(0,0,0,0.15)',
  },
}));

// 混淆矩阵样式
const ConfusionMatrix = styled(Box)(({ theme }) => ({
  display: 'flex',
  flexDirection: 'column',
  gap: '8px',
  maxWidth: '600px',
  margin: '0 auto',
}));

const MatrixCell = styled(Box)<{ value: number; isDiagonal?: boolean }>(({ theme, value, isDiagonal }) => ({
  width: '80px',
  height: '50px',
  padding: theme.spacing(1),
  textAlign: 'center',
  borderRadius: '8px',
  fontWeight: 600,
  fontSize: '14px',
  display: 'flex',
  alignItems: 'center',
  justifyContent: 'center',
  color: isDiagonal ? '#2d3748' : '#4a5568',
  backgroundColor: isDiagonal 
    ? `rgba(78, 205, 196, ${Math.min(value / 100, 1)})`
    : `rgba(102, 126, 234, ${Math.min(value / 100, 1)})`,
  border: isDiagonal ? '2px solid #4ECDC4' : '1px solid #667eea',
  transition: 'all 0.3s ease',
  '&:hover': {
    transform: 'scale(1.05)',
    boxShadow: '0 4px 16px rgba(0,0,0,0.1)',
  },
}));

const ModelAnalysisPage: React.FC = () => {
  const [trainingData, setTrainingData] = useState<any>(null);
  const [confusionMatrix, setConfusionMatrix] = useState<any>(null);
  const [classMetrics, setClassMetrics] = useState<any[]>([]);
  const [modelInfo, setModelInfo] = useState<any>(null);
  const [loading, setLoading] = useState<boolean>(true);
  const [error, setError] = useState<string | null>(null);

  // 获取训练指标数据
  const fetchTrainingMetrics = async () => {
    try {
      setLoading(true);
      const response = await fetch('/api/training_metrics');
      
      if (!response.ok) {
        throw new Error('HTTP error! status: ' + response.status);
      }

      const data = await response.json();
      console.log('Training metrics data:', data);
      setTrainingData(data.training_data);
      setConfusionMatrix(data.confusion_matrix);
      setClassMetrics(data.class_metrics);
      setModelInfo(data.model_info);
      console.log('Class metrics:', data.class_metrics);
      console.log('Class metrics structure:', data.class_metrics.map((item: any) => ({
        keys: Object.keys(item),
        values: Object.values(item)
      })));
    } catch (err) {
      setError('获取训练指标数据失败，请稍后重试');
      console.error(err);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchTrainingMetrics();
  }, []);

  // 准备训练曲线数据
  const prepareTrainingData = () => {
    if (!trainingData) return [];
    
    return trainingData.epochs.map((epoch: number, index: number) => ({
      epoch,
      train_loss: trainingData.train_loss[index],
      val_loss: trainingData.val_loss[index],
      train_acc: trainingData.train_acc[index] * 100,
      val_acc: trainingData.val_acc[index] * 100,
    }));
  };

  // 准备混淆矩阵数据
  const prepareConfusionMatrix = () => {
    if (!confusionMatrix) return { labels: [], matrix: [] };
    
    return {
      labels: confusionMatrix.labels,
      matrix: confusionMatrix.matrix.map((row: number[], rowIndex: number) => 
        row.map((cell: number, colIndex: number) => ({
          value: cell,
          isDiagonal: rowIndex === colIndex,
          label: confusionMatrix.labels[colIndex]
        }))
      )
    };
  };

  if (loading) {
    return (
      <MainContainer maxWidth="xl">
        <MainPaper elevation={0}>
          <Box sx={{ display: 'flex', justifyContent: 'center', alignItems: 'center', minHeight: '400px' }}>
            <Box sx={{ textAlign: 'center' }}>
              <CircularProgress size={60} sx={{ color: '#667eea', mb: 2 }} />
              <Typography variant="h6" sx={{ color: '#4a5568' }}>
                正在加载模型分析数据...
              </Typography>
            </Box>
          </Box>
        </MainPaper>
      </MainContainer>
    );
  }

  if (error) {
    return (
      <MainContainer maxWidth="xl">
        <MainPaper elevation={0}>
          <Alert severity="error" sx={{ borderRadius: '12px' }}>
            {error}
          </Alert>
        </MainPaper>
      </MainContainer>
    );
  }

  const chartData = prepareTrainingData();
  const matrixData = prepareConfusionMatrix();

  return (
    <MainContainer maxWidth="xl">
      <MainPaper elevation={0}>
        <Fade in timeout={800}>
          <GradientTitle variant="h3">
            🧠 模型训练过程分析
          </GradientTitle>
        </Fade>

        <Grow in timeout={1000}>
          <Box my={5}>
            {/* 模型基本信息 */}
            {modelInfo && (
              <Fade in timeout={1200}>
                <Box sx={{ mb: 5 }}>
                  <Typography
                    variant="h4"
                    component="h2"
                    gutterBottom
                    sx={{
                      color: '#2d3748',
                      fontWeight: 700,
                      mb: 3,
                      display: 'flex',
                      alignItems: 'center',
                      gap: 2
                    }}
                  >
                    <Biotech sx={{ color: '#667eea', fontSize: 40 }} />
                    模型架构信息
                  </Typography>
                  
                  <Grid container spacing={3}>
                    {Object.entries(modelInfo).map(([key, value], index) => (
                      <Grid size={{ xs: 12, sm: 6, md: 3 }} key={key}>
                        <Fade in timeout={1400 + index * 200}>
                          <StatsCard>
                            <CardContent sx={{ p: 0 }}>
                              <Box sx={{ p: 3, textAlign: 'center' }}>
                                <Typography
                                  variant="h4"
                                  sx={{
                                    color: '#667eea',
                                    fontWeight: 800,
                                    mb: 1,
                                    animation: `${pulse} 2s infinite`
                                  }}
                                >
                                  {typeof value === 'number' ? value.toLocaleString() : String(value)}
                                </Typography>
                                <Typography
                                  variant="body1"
                                  sx={{
                                    color: '#4a5568',
                                    fontWeight: 600,
                                    textTransform: 'capitalize'
                                  }}
                                >
                                  {key.replace(/_/g, ' ')}
                                </Typography>
                              </Box>
                            </CardContent>
                          </StatsCard>
                        </Fade>
                      </Grid>
                    ))}
                  </Grid>
                </Box>
              </Fade>
            )}

            {/* 训练曲线 */}
            <Fade in timeout={1600}>
              <Box sx={{ mb: 5 }}>
                <Typography
                  variant="h4"
                  component="h2"
                  gutterBottom
                  sx={{
                    color: '#2d3748',
                    fontWeight: 700,
                    mb: 3,
                    display: 'flex',
                    alignItems: 'center',
                    gap: 2
                  }}
                >
                  <TrendingUp sx={{ color: '#667eea', fontSize: 40 }} />
                  训练过程可视化
                </Typography>

                <Grid container spacing={4}>
                  <Grid size={{ xs: 12, lg: 6 }}>
                    <ChartContainer>
                      <Typography
                        variant="h6"
                        component="h3"
                        gutterBottom
                        sx={{
                          color: '#2d3748',
                          fontWeight: 700,
                          mb: 3,
                          display: 'flex',
                          alignItems: 'center',
                          gap: 1
                        }}
                      >
                        <Analytics sx={{ color: '#667eea' }} />
                        损失函数变化
                      </Typography>
                      <ResponsiveContainer width="100%" height="85%">
                        <LineChart data={chartData}>
                          <CartesianGrid strokeDasharray="3 3" stroke="#e2e8f0" />
                          <XAxis 
                            dataKey="epoch" 
                            tick={{ fill: '#4a5568', fontSize: 12 }}
                            axisLine={{ stroke: '#e2e8f0' }}
                          />
                          <YAxis 
                            tick={{ fill: '#4a5568', fontSize: 12 }}
                            axisLine={{ stroke: '#e2e8f0' }}
                          />
                          <Tooltip 
                            contentStyle={{
                              backgroundColor: 'rgba(255,255,255,0.95)',
                              border: 'none',
                              borderRadius: '12px',
                              boxShadow: '0 8px 32px rgba(0,0,0,0.1)'
                            }}
                          />
                          <Legend />
                          <Line 
                            type="monotone" 
                            dataKey="train_loss" 
                            stroke="#667eea" 
                            strokeWidth={3}
                            name="训练损失"
                            dot={{ fill: '#667eea', strokeWidth: 2, r: 4 }}
                          />
                          <Line 
                            type="monotone" 
                            dataKey="val_loss" 
                            stroke="#4ECDC4" 
                            strokeWidth={3}
                            name="验证损失"
                            dot={{ fill: '#4ECDC4', strokeWidth: 2, r: 4 }}
                          />
                        </LineChart>
                      </ResponsiveContainer>
                    </ChartContainer>
                  </Grid>

                  <Grid size={{ xs: 12, lg: 6 }}>
                    <ChartContainer>
                      <Typography
                        variant="h6"
                        component="h3"
                        gutterBottom
                        sx={{
                          color: '#2d3748',
                          fontWeight: 700,
                          mb: 3,
                          display: 'flex',
                          alignItems: 'center',
                          gap: 1
                        }}
                      >
                        <Speed sx={{ color: '#667eea' }} />
                        准确率变化
                      </Typography>
                      <ResponsiveContainer width="100%" height="85%">
                        <LineChart data={chartData}>
                          <CartesianGrid strokeDasharray="3 3" stroke="#e2e8f0" />
                          <XAxis 
                            dataKey="epoch" 
                            tick={{ fill: '#4a5568', fontSize: 12 }}
                            axisLine={{ stroke: '#e2e8f0' }}
                          />
                          <YAxis 
                            tick={{ fill: '#4a5568', fontSize: 12 }}
                            axisLine={{ stroke: '#e2e8f0' }}
                          />
                          <Tooltip 
                            contentStyle={{
                              backgroundColor: 'rgba(255,255,255,0.95)',
                              border: 'none',
                              borderRadius: '12px',
                              boxShadow: '0 8px 32px rgba(0,0,0,0.1)'
                            }}
                          />
                          <Legend />
                          <Line 
                            type="monotone" 
                            dataKey="train_acc" 
                            stroke="#FF6B6B" 
                            strokeWidth={3}
                            name="训练准确率"
                            dot={{ fill: '#FF6B6B', strokeWidth: 2, r: 4 }}
                          />
                          <Line 
                            type="monotone" 
                            dataKey="val_acc" 
                            stroke="#96CEB4" 
                            strokeWidth={3}
                            name="验证准确率"
                            dot={{ fill: '#96CEB4', strokeWidth: 2, r: 4 }}
                          />
                        </LineChart>
                      </ResponsiveContainer>
                    </ChartContainer>
                  </Grid>
                </Grid>
              </Box>
            </Fade>

            {/* 混淆矩阵 */}
            <Fade in timeout={1800}>
              <Box sx={{ mb: 5 }}>
                <Typography
                  variant="h4"
                  component="h2"
                  gutterBottom
                  sx={{
                    color: '#2d3748',
                    fontWeight: 700,
                    mb: 3,
                    display: 'flex',
                    alignItems: 'center',
                    gap: 2
                  }}
                >
                  <Psychology sx={{ color: '#667eea', fontSize: 40 }} />
                  混淆矩阵分析
                </Typography>

                <Grid container spacing={4} alignItems="center">
                  <Grid size={{ xs: 12, md: 6 }}>
                    <ChartContainer sx={{ height: '500px' }}>
                      <Typography
                        variant="h6"
                        component="h3"
                        gutterBottom
                        sx={{
                          color: '#2d3748',
                          fontWeight: 700,
                          mb: 3,
                          textAlign: 'center'
                        }}
                      >
                        预测结果混淆矩阵
                      </Typography>
                      <Box sx={{ display: 'flex', justifyContent: 'center' }}>
                        <ConfusionMatrix>
                          {/* 列标题 */}
                          <Box sx={{ display: 'flex', mb: 2, gap: 1 }}>
                            <Box sx={{ width: '80px' }}></Box>
                            {matrixData.labels.map((label: string, colIndex: number) => (
                              <Box
                                key={`col-${colIndex}`}
                                sx={{
                                  width: '80px',
                                  height: '30px',
                                  display: 'flex',
                                  alignItems: 'center',
                                  justifyContent: 'center',
                                  fontSize: '12px',
                                  fontWeight: 'bold',
                                  color: '#4a5568'
                                }}
                              >
                                {label}
                              </Box>
                            ))}
                          </Box>
                          
                          {/* 矩阵内容 */}
                          {matrixData.matrix.map((row: any[], rowIndex: number) => (
                            <Box key={`row-${rowIndex}`} sx={{ display: 'flex', mb: 2, gap: 1 }}>
                              {/* 行标题 */}
                              <Box
                                sx={{
                                  width: '80px',
                                  height: '50px',
                                  display: 'flex',
                                  alignItems: 'center',
                                  justifyContent: 'center',
                                  fontSize: '12px',
                                  fontWeight: 'bold',
                                  color: '#4a5568'
                                }}
                              >
                                {matrixData.labels[rowIndex]}
                              </Box>
                              
                              {/* 矩阵单元格 */}
                              {row.map((cell: any, colIndex: number) => (
                                <MatrixCell
                                  key={`${rowIndex}-${colIndex}`}
                                  value={cell?.value || 0}
                                  isDiagonal={cell?.isDiagonal}
                                >
                                  {cell?.value || 0}
                                </MatrixCell>
                              ))}
                            </Box>
                          ))}
                        </ConfusionMatrix>
                      </Box>
                    </ChartContainer>
                  </Grid>

                  <Grid size={{ xs: 12, md: 6 }}>
                    <ChartContainer sx={{ height: '500px' }}>
                      <Typography
                        variant="h6"
                        component="h3"
                        gutterBottom
                        sx={{
                          color: '#2d3748',
                          fontWeight: 700,
                          mb: 3,
                          textAlign: 'center'
                        }}
                      >
                        各类别性能指标
                      </Typography>
                      {(() => {
                        const shouldShow = classMetrics && Array.isArray(classMetrics) && classMetrics.length > 0;
                        console.log('Should show chart:', shouldShow, 'classMetrics:', classMetrics);
                        return shouldShow;
                      })() ? (
                        <div style={{ 
                          width: '100%', 
                          height: '400px', 
                          padding: '20px',
                          backgroundColor: '#f8fafc',
                          borderRadius: '12px',
                          border: '1px solid #e2e8f0',
                          position: 'relative'
                        }}>
                          <div style={{ 
                            display: 'flex', 
                            justifyContent: 'space-between', 
                            alignItems: 'end', 
                            height: '300px',
                            marginBottom: '20px',
                            padding: '0 20px'
                          }}>
                            {classMetrics.map((metric: any, index: number) => (
                              <div key={index} style={{ 
                                display: 'flex', 
                                flexDirection: 'column', 
                                alignItems: 'center',
                                flex: 1,
                                margin: '0 5px'
                              }}>
                                <div style={{ 
                                  display: 'flex', 
                                  flexDirection: 'row', 
                                  alignItems: 'end',
                                  height: '100%',
                                  justifyContent: 'center',
                                  gap: '3px'
                                }}>
                                  {/* 精确率 */}
                                  <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center' }}>
                                    <div style={{
                                      fontSize: '10px',
                                      color: '#4a5568',
                                      fontWeight: '500',
                                      marginBottom: '2px',
                                      textAlign: 'center'
                                    }}>
                                      {(metric.precision * 100).toFixed(1)}%
                                    </div>
                                    <div style={{
                                      width: '15px',
                                      height: `${metric.precision * 250}px`,
                                      backgroundColor: '#667eea',
                                      borderRadius: '4px 4px 0 0',
                                      minHeight: '2px'
                                    }} title={`精确率: ${(metric.precision * 100).toFixed(1)}%`} />
                                  </div>
                                  
                                  {/* 召回率 */}
                                  <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center' }}>
                                    <div style={{
                                      fontSize: '10px',
                                      color: '#4a5568',
                                      fontWeight: '500',
                                      marginBottom: '2px',
                                      textAlign: 'center'
                                    }}>
                                      {(metric.recall * 100).toFixed(1)}%
                                    </div>
                                    <div style={{
                                      width: '15px',
                                      height: `${metric.recall * 250}px`,
                                      backgroundColor: '#4ECDC4',
                                      borderRadius: '4px 4px 0 0',
                                      minHeight: '2px'
                                    }} title={`召回率: ${(metric.recall * 100).toFixed(1)}%`} />
                                  </div>
                                  
                                  {/* F1分数 */}
                                  <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center' }}>
                                    <div style={{
                                      fontSize: '10px',
                                      color: '#4a5568',
                                      fontWeight: '500',
                                      marginBottom: '2px',
                                      textAlign: 'center'
                                    }}>
                                      {(metric.f1_score * 100).toFixed(1)}%
                                    </div>
                                    <div style={{
                                      width: '15px',
                                      height: `${metric.f1_score * 250}px`,
                                      backgroundColor: '#FF6B6B',
                                      borderRadius: '4px 4px 0 0',
                                      minHeight: '2px'
                                    }} title={`F1分数: ${(metric.f1_score * 100).toFixed(1)}%`} />
                                  </div>
                                </div>
                                
                                {/* 类别标签 */}
                                <div style={{ 
                                  marginTop: '10px', 
                                  fontSize: '12px', 
                                  color: '#4a5568',
                                  textAlign: 'center',
                                  fontWeight: '500'
                                }}>
                                  {metric.class}
                                </div>
                              </div>
                            ))}
                          </div>
                          
                          {/* 图例 */}
                          <div style={{ 
                            display: 'flex', 
                            justifyContent: 'center', 
                            gap: '20px',
                            marginTop: '10px'
                          }}>
                            <div style={{ display: 'flex', alignItems: 'center', gap: '5px' }}>
                              <div style={{ 
                                width: '12px', 
                                height: '12px', 
                                backgroundColor: '#667eea',
                                borderRadius: '2px'
                              }} />
                              <span style={{ fontSize: '12px', color: '#4a5568', fontWeight: '500' }}>精确率</span>
                            </div>
                            <div style={{ display: 'flex', alignItems: 'center', gap: '5px' }}>
                              <div style={{ 
                                width: '12px', 
                                height: '12px', 
                                backgroundColor: '#4ECDC4',
                                borderRadius: '2px'
                              }} />
                              <span style={{ fontSize: '12px', color: '#4a5568', fontWeight: '500' }}>召回率</span>
                            </div>
                            <div style={{ display: 'flex', alignItems: 'center', gap: '5px' }}>
                              <div style={{ 
                                width: '12px', 
                                height: '12px', 
                                backgroundColor: '#FF6B6B',
                                borderRadius: '2px'
                              }} />
                              <span style={{ fontSize: '12px', color: '#4a5568', fontWeight: '500' }}>F1分数</span>
                            </div>
                          </div>
                          
                          {/* 说明文字 */}
                          <div style={{ 
                            textAlign: 'center', 
                            marginTop: '8px',
                            fontSize: '11px', 
                            color: '#64748b'
                          }}>
                            每个类别显示三个并排的指标柱状图
                          </div>
                          
                          {/* Y轴标签 */}
                          <div style={{ 
                            position: 'absolute',
                            left: '10px',
                            top: '50%',
                            transform: 'translateY(-50%) rotate(-90deg)',
                            fontSize: '12px',
                            color: '#64748b',
                            fontWeight: '500'
                          }}>
                            性能指标
                          </div>
                        </div>
                      ) : (
                        <Box sx={{ 
                          display: 'flex', 
                          flexDirection: 'column',
                          alignItems: 'center', 
                          justifyContent: 'center', 
                          height: '200px',
                          color: '#4a5568'
                        }}>
                          <Typography>暂无数据</Typography>
                          <Typography variant="caption" sx={{ mt: 1 }}>
                            数据状态: {classMetrics ? `已加载 ${classMetrics.length} 条记录` : '未加载'}
                          </Typography>
                        </Box>
                      )}
                    </ChartContainer>
                  </Grid>
                </Grid>
              </Box>
            </Fade>

            {/* 模型性能总结 */}
            <Fade in timeout={2000}>
              <Box>
                <Typography
                  variant="h4"
                  component="h2"
                  gutterBottom
                  sx={{
                    color: '#2d3748',
                    fontWeight: 700,
                    mb: 3,
                    display: 'flex',
                    alignItems: 'center',
                    gap: 2
                  }}
                >
                  <CheckCircle sx={{ color: '#4ECDC4', fontSize: 40 }} />
                  模型性能总结
                </Typography>

                <Grid container spacing={3}>
                  {classMetrics.map((metric, index) => (
                    <Grid size={{ xs: 12, sm: 6, md: 3 }} key={metric.class}>
                      <Fade in timeout={2200 + index * 200}>
                        <StatsCard>
                          <CardContent sx={{ p: 0 }}>
                            <Box sx={{ p: 3, textAlign: 'center' }}>
                              <Typography
                                variant="h6"
                                sx={{
                                  color: '#2d3748',
                                  fontWeight: 700,
                                  mb: 2
                                }}
                              >
                                {metric.class}
                              </Typography>
                              <Box sx={{ display: 'flex', justifyContent: 'space-between', mb: 1 }}>
                                <Typography variant="body2" sx={{ color: '#4a5568' }}>
                                  精确率:
                                </Typography>
                                <Typography variant="body2" sx={{ color: '#667eea', fontWeight: 600 }}>
                                  {(metric.precision * 100).toFixed(1)}%
                                </Typography>
                              </Box>
                              <Box sx={{ display: 'flex', justifyContent: 'space-between', mb: 1 }}>
                                <Typography variant="body2" sx={{ color: '#4a5568' }}>
                                  召回率:
                                </Typography>
                                <Typography variant="body2" sx={{ color: '#4ECDC4', fontWeight: 600 }}>
                                  {(metric.recall * 100).toFixed(1)}%
                                </Typography>
                              </Box>
                              <Box sx={{ display: 'flex', justifyContent: 'space-between', mb: 2 }}>
                                <Typography variant="body2" sx={{ color: '#4a5568' }}>
                                  F1分数:
                                </Typography>
                                <Typography variant="body2" sx={{ color: '#FF6B6B', fontWeight: 600 }}>
                                  {(metric.f1_score * 100).toFixed(1)}%
                                </Typography>
                              </Box>
                              <Chip
                                label={metric.f1_score > 0.9 ? '优秀' : metric.f1_score > 0.8 ? '良好' : '一般'}
                                size="small"
                                sx={{
                                  backgroundColor: metric.f1_score > 0.9 ? '#4ECDC420' : 
                                    metric.f1_score > 0.8 ? '#FFD93D20' : '#FF6B6B20',
                                  color: metric.f1_score > 0.9 ? '#4ECDC4' : 
                                    metric.f1_score > 0.8 ? '#FFD93D' : '#FF6B6B',
                                  fontWeight: 600
                                }}
                              />
                            </Box>
                          </CardContent>
                        </StatsCard>
                      </Fade>
                    </Grid>
                  ))}
                </Grid>
              </Box>
            </Fade>
          </Box>
        </Grow>
      </MainPaper>
    </MainContainer>
  );
};

export default ModelAnalysisPage;
